<template>
  <div class="app-container">
    <el-form
      :model="queryEquipmentParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="70px"
      :rules="queryEquipmentParamsRules"
    >
      <el-form-item label="设备ID" prop="equipmentId">
        <el-input
          v-model="queryEquipmentParams.equipmentId"
          placeholder="设备ID"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="设备名称" prop="equipmentName">
        <el-input
          v-model="queryEquipmentParams.equipmentName"
          placeholder="设备名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          :disabled="currentEquipmentId == null"
          v-hasPermi="['equipment:param:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['equipment:param:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['equipment:param:remove']"
          >删除</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-download"
          size="mini"
          :loading="btnLoading"
          @click="handleExport"
          v-hasPermi="['equipment:param:export']"
          >导出</el-button
        >
      </el-col>
      <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
    </el-row>

    <el-row :gutter="18">
      <el-col :span="4">
        <el-table
          :cell-style="{ padding: this.tablePadding }"
          ref="equipmentTable"
          :data="equipmentList"
          :height="tableHeight"
          highlight-current-row
          @current-change="handleCurrentEquipmentChange"
          border
        >
          <template slot="empty">
            <div>
              <span>设备不存在</span>
            </div>
          </template>
          <el-table-column label="设备ID" align="center" prop="equipmentId" />

          <el-table-column
            label="设备名称"
            align="center"
            prop="equipmentName"
          />
        </el-table>

        <pagination
          v-show="equipmentTotal > 0"
          small
          layout="prev, pager, next"
          :total="equipmentTotal"
          :page.sync="queryEquipmentParams.pageNum"
          :limit.sync="queryEquipmentParams.pageSize"
          @pagination="getList"
        />
      </el-col>

      <el-col :span="20">
        <el-table
          :cell-style="{ padding: this.tablePadding }"
          v-loading="loading"
          :data="paramList"
          @selection-change="handleSelectionChange"
          :height="tableHeight"
          border
        >
          <template slot="empty">
            <div>
              <span>参数不存在,请选择设备或添加参数</span>
            </div>
          </template>
          <!-- <el-table-column type="selection" width="55" align="center" /> -->
          <!-- <el-table-column
            label="参数ID"
            align="center"
            prop="equipmentParamId"
          />
          <el-table-column label="设备ID" align="center" prop="equipmentId" /> -->
          <el-table-column
            label="参数名称"
            align="center"
            prop="equipmentParam"
          />
          <el-table-column
            label="采集字段"
            align="center"
            prop="collectColumn"
          />
          <el-table-column
            label="创建者"
            align="center"
            prop="createBy"
          />
          <!-- <el-table-column
            label="是否报警"
            align="center"
            prop="isAlarm"
            :formatter="ifAlarmFormat"
          />
          <el-table-column label="报警上限" align="center" prop="alarmUp" />
          <el-table-column label="报警下限" align="center" prop="alarmDown" />
          <el-table-column
            label="预警上限"
            align="center"
            prop="earlyAlarmUp"
          />
          <el-table-column
            label="预警下限"
            align="center"
            prop="earlyAlarmDown"
          />
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
            min-width="120px"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['equipment:param:edit']"
                >修改</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['equipment:param:remove']"
                >删除</el-button
              >
            </template>
          </el-table-column> -->
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getParamList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改设备参数对话框 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form
        ref="form"
        :inline="true"
        layout="inline"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="设备ID" prop="equipmentId">
          <el-input disabled v-model="form.equipmentId" placeholder="设备ID" />
        </el-form-item>
        <el-form-item label="参数名称" prop="equipmentParam">
          <el-input
            v-model="form.equipmentParam"
            placeholder="请输入参数名称"
          />
        </el-form-item>
        <el-form-item label="采集字段" prop="collectColumn">
          <el-input v-model="form.collectColumn" placeholder="请输入采集字段" />
        </el-form-item>
        <el-form-item label="是否报警" prop="isAlarm">
          <el-radio v-model="form.isAlarm" :label="1">是</el-radio>
          <el-radio v-model="form.isAlarm" :label="0">否</el-radio>
        </el-form-item>
        <el-form-item label="报警上限" prop="alarmUp" v-if="form.isAlarm==1">
          <el-input
            v-model="form.alarmUp"
            @blur="form.alarmUp = $event.target.value"
            oninput="value=value.replace(/[^\d^\.]/g,'')"
            placeholder="请输入报警上限"
          />
        </el-form-item>
        <el-form-item label="报警下限" prop="alarmDown" v-if="form.isAlarm==1">
          <el-input
            v-model="form.alarmDown"
            @blur="form.alarmDown = $event.target.value"
            oninput="value=value.replace(/[^\d^\.]/g,'')"
            placeholder="请输入报警下限"
          />
        </el-form-item>
        <el-form-item label="预警上限" prop="earlyAlarmUp" v-if="form.isAlarm==1">
          <el-input
            v-model="form.earlyAlarmUp"
            @blur="form.earlyAlarmUp = $event.target.value"
            oninput="value=value.replace(/[^\d^\.]/g,'')"
            placeholder="请输入预警上限"
          />
        </el-form-item>
        <el-form-item label="预警下限" prop="earlyAlarmDown" v-if="form.isAlarm==1">
          <el-input
            v-model="form.earlyAlarmDown"
            @blur="form.earlyAlarmDown = $event.target.value"
            oninput="value=value.replace(/[^\d^\.]/g,'')"
            placeholder="请输入预警下限"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="btnLoading"  v-funThrottle="[submitForm]">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listParam,
  getParam,
  delParam,
  addParam,
  updateParam,
  listEquipment,
} from "@/api/equipment/param";

export default {
  name: "Param",
  components: {},
  data() {
    // 报警上限
    var checkAlarmUp = (rule, value, callback) => {
      if (parseFloat(this.form.earlyAlarmUp) > parseFloat(value)) {
        return callback(new Error("请检查报警范围"));
      } else {
        return callback();
      }
    };
    // 预警上限
    var checkEarlyAlarmUp = (rule, value, callback) => {
      if (
        parseFloat(this.form.alarmUp) < parseFloat(value) ||
        parseFloat(value) < parseFloat(this.form.earlyAlarmDown)
      ) {
        return callback(new Error("请检查预警范围"));
      } else {
        return callback();
      }
    };
    //  预警下限
    var checkEarlyAlarmDown = (rule, value, callback) => {
      if (
        parseFloat(this.form.earlyAlarmUp) < parseFloat(value) ||
        parseFloat(value) < parseFloat(this.form.alarmDown)
      ) {
        return callback(new Error("请检查预警范围"));
      } else {
        return callback();
      }
    };
    //  报警下限
    var checkAlarmDown = (rule, value, callback) => {
      if (parseFloat(value) > parseFloat(this.form.earlyAlarmDown)) {
        return callback(new Error("请检查报警范围"));
      } else {
        return callback();
      }
    };
    return {
      // 遮罩层
      loading: true,
      btnLoading:false,
      // 选中数组
      ids: [],
      selectNames: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      equipmentTotal:0,
      // 设备参数表格数据
      paramList: [],

      allEquipmentList: [],

      // 设备列表
      equipmentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      tableHeight: window.innerHeight - 275,
      currentEquipmentId: null,
      // 查询参数
      queryEquipmentParams: {
        equipmentId: null,
        equipmentName: null,
        pageNum: 1,
        status:1,
        pageSize: 10,
      },
      queryEquipmentParamsRules: {
        // equipmentId: [
        //   { required: true, message: "设备不能为空", trigger: "blur" }
        // ]
      },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        equipmentId: null,
        equipmentParam: null,
        collectColumn: null,
      },

      // 表单参数
      form: {},
      // 表单校验
      rules: {
        equipmentId: [
          { required: true, message: "设备不能为空", trigger: "blur" },
        ],
        equipmentParam: [
          { required: true, message: "参数名称不能为空", trigger: "blur" },
        ],
        collectColumn: [
          { required: true, message: "采集字段不能为空", trigger: "blur" },
        ],
        isAlarm: [
          { required: true, message: "是否报警不能为空", trigger: "blur" },
        ],
        alarmUp: [
          { required: true, message: "报警上限不能为空", trigger: "blur" },
          { validator: checkAlarmUp, trigger: "blur" },
        ],
        earlyAlarmUp: [
          { required: true, message: "预警上限不能为空", trigger: "blur" },
          { validator: checkEarlyAlarmUp, trigger: "blur" },
        ],
        earlyAlarmDown: [
          { required: true, message: "预警下限不能为空", trigger: "blur" },
          { validator: checkEarlyAlarmDown, trigger: "blur" },
        ],
        alarmDown: [
          { required: true, message: "报警下限不能为空", trigger: "blur" },
          { validator: checkAlarmDown, trigger: "blur" },
        ],
      },
    };
  },
  created() {
    window.addEventListener("resize", this.getHeight);
  },
  destroyed() {
    window.removeEventListener("resize", this.getHeight);
  },
  mounted() {
    this.queryEquipmentParams.equipmentId = this.$route.query.equipmentId;
    this.queryEquipmentParams.equipmentName = this.$route.query.equipmentName;
    this.getList();
    this.allEquipmentList = this.equipmentList;
  },
  watch: {
    $route() {
      this.queryEquipmentParams.equipmentId = this.$route.query.equipmentId;
      this.queryEquipmentParams.equipmentName = this.$route.query.equipmentName;
      if (this.queryEquipmentParams.equipmentId != null) {
        this.getList();
      }
    },
  },
  methods: {
    /** 查询设备参数列表 */
    getList() {
      this.loading = true;
      listEquipment(this.queryEquipmentParams).then((response) => {
        this.equipmentList = response.rows;
        this.$nextTick(function() {
        this.$refs.equipmentTable.setCurrentRow(this.equipmentList[0])
      })
        this.equipmentTotal = response.total;
        this.loading = false;

        // if (this.equipmentList.length > 0) {
        //   this.handleCurrentEquipmentChange(this.equipmentList[0]);
        // }
      });
    },
    getParamList() {
      this.loading = true;
      listParam(this.queryParams).then((response) => {
        this.paramList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getHeight() {
      this.tableHeight = window.innerHeight - 275;
    },
    ifAlarmFormat(row, column) {
      if (row.isAlarm == 0) {
        return "否";
      } else if (row.isAlarm == 1) {
        return "是";
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        equipmentParamId: null,
        equipmentId: null,
        equipmentParam: null,
        collectColumn: null,
        isTechnologyColumn: null,
        isAlarm: 1,
        alarmUp: null,
        alarmDown: null,
        earlyAlarmUp: null,
        earlyAlarmDown: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.queryEquipmentParams.pageNum = 1;
      this.paramList = [];
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.currentEquipmentId = null;
      this.queryEquipmentParams.equipmentName = null;
      this.queryEquipmentParams.equipmentId = null;

      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.equipmentParamId);
      this.selectNames = selection.map((item) => item.equipmentParam);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    handleCurrentEquipmentChange(selection) {
      if (selection != null) {
        this.currentEquipmentId = selection.equipmentId;
        this.queryParams.equipmentId = selection.equipmentId;
        this.getParamList();
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.equipmentId = this.currentEquipmentId;
      this.open = true;
      this.title = "添加设备参数";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const equipmentParamId = row.equipmentParamId || this.ids;
      getParam(equipmentParamId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改设备参数";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.btnLoading=true
          if (this.form.equipmentParamId != null) {
            updateParam(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getParamList();
            this.btnLoading=false
            }).catch(()=>{
              this.btnLoading=false
            });
          } else {
            addParam(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getParamList();
            this.btnLoading=false
            }).catch(()=>{
              this.btnLoading=false
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const equipmentParamIds = row.equipmentParamId || this.ids;
      const name = row.equipmentParam || this.selectNames;
      this.$confirm(
        '是否确认删除设备参数名称为"' + name + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",closeOnClickModal:false,
          type: "warning",
        }
      )
        .then(function () {
          return delParam(equipmentParamIds);
        })
        .then(() => {
          this.getParamList();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.btnLoading=true
      this.download(
        "equipment/param/export",
        {
          ...this.queryParams,
        },
        `equipment_param.xlsx`,
        '',
        ()=>{
          this.btnLoading=false
        }
      );
    },
  },
};
</script>

<style>
.el-table th {
  display: table-cell !important;
}
</style>